<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Order, Business, Agent, AgentArea, Config, OrderGoods, Compent};
use think\Db;
use think\facade\Log;

class OrderFinish extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('OrderFinish')->setDescription('订单自动确认等操作');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //15分钟未支付自动取消
        $fwtimes = date('Y-m-d H:i:s', time() - 600);
        (new Order())->where(['status' => 1])->where('created', '<', $fwtimes)->chunk(10, function ($lists) {
            foreach ($lists as $list) {
                Db::startTrans();
                try {
                    (new Order())->where('id', $list['id'])->where('status', 1)->update(['status' => 5, 'caceltimes' => date('Y-m-d H:i:s')]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage();
                    continue;
                }
                echo '取消成功';
            }
        });
        //12小时后自动确认订单
        $fwtimes = date('Y-m-d H:i:s', time() - 12 * 3600);
        (new Order())->where(['status' => 3, 'shouhou' => 1])->where('fwtimes', '<', $fwtimes)->chunk(10, function ($lists) {
            foreach ($lists as $list) {
                Db::startTrans();
                try {
                    $finishtimes = date('Y-m-d H:i:s');
                    (new Order())->where('id', $list['id'])->update(['status' => 4, 'finishtimes' => $finishtimes]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage();
                    continue;
                }
                echo '确认成功';
            }
        });
    }
}